export function useTable(tableProps) {
  const tableRef = ref(null);
  const loadedRef = ref(false);



  let stopWatch;

  function register(instance) {
    onUnmounted(() => {
      console.log('onUnmounted')
      tableRef.value = null;
      loadedRef.value = null;
    });

    if (unref(loadedRef) && instance === unref(tableRef)) {
      return;
    }

    tableRef.value = instance;
    tableProps && instance.setProps(tableProps);
    loadedRef.value = true;
    stopWatch?.();
    stopWatch = watch(
      () => tableProps,
      () => {
        tableProps && instance.setProps(tableProps);
      },
      {
        immediate: true,
        deep: true,
      },
    );

    return instance;
  }

  function getTableInstance() {
    const table = unref(tableRef);
    if (!table) {
      console.error(
        'The table instance has not been obtained yet, please make sure the table is presented when performing the table operation!',
      );
    }
    return table || {};
  }

  const methods = {
    reloadList: async opt => {
      await getTableInstance().reloadList(opt);
    },

    refreshList: async opt => {
      console.log('getTableInstance', getTableInstance());
      await ((getTableInstance().refreshList && getTableInstance().refreshList(opt)) || '');
    },
    setProps: props => {
      getTableInstance().setProps(props);
    },


  };


  onShow(() => {
    const table = unref(tableRef);
    // debugger
    console.log(table, 'tabletable------------')
    if (table && table.getProps.showRefresh) {
      methods.refreshList()
    }
  })

  return [register, methods];
}
